package com.holly.unit.bpmn.activiti.ext;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.holly.unit.bpmn.activiti.entity.ActivitiZBusiness;
import com.holly.unit.bpmn.activiti.mapper.ActivitiZBusinessMapper;
import com.holly.unit.db.api.pojo.db.TableFieldInfo;
import com.holly.unit.db.api.pojo.druid.DruidProperties;
import com.holly.unit.db.api.util.DatabaseUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 类描述: 流程业务扩展实现类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/2/22 11:02
 */
@Service
public class ActivitiZBusinessService extends ServiceImpl<ActivitiZBusinessMapper, ActivitiZBusiness> {

    @Resource
    private DruidProperties druidProperties;

    public List<ActivitiZBusiness> findByProcDefId(String id) {
        return this.list(new LambdaQueryWrapper<ActivitiZBusiness>().eq(ActivitiZBusiness::getProcDefId,id));
    }

    /***
     * 保存业务表单数据到数据库表
     * 该方法相对通用，复杂业务单独定制，套路类似
     * @param tableId 业务表中的数据id
     * @param paramsMap
     */
    public void saveApplyForm(String tableId, Map<String,Object> paramsMap) {
        String tableName = String.valueOf(paramsMap.get("tableName"));
        String filedNames = String.valueOf(paramsMap.get("filedNames"));
        Map<String,Object> filedValues = (Map<String, Object>) paramsMap.get("formDataMap");
        Map<String, Object> busiData = this.baseMapper.getBusiData(tableId, tableName);
        String[] fileds = filedNames.split(",");
        //查询数据库表字段
        List<TableFieldInfo> tableFields = DatabaseUtil.getTableFields(druidProperties, tableName);
        Map<String, TableFieldInfo> table = tableFields.stream().collect(Collectors.toMap(TableFieldInfo::getColumnName, Function.identity()));
        if (MapUtil.isEmpty(busiData)){ //没有，新增逻辑
            StringBuilder filedsB = new StringBuilder("id");
            StringBuilder filedsVB = new StringBuilder("'"+tableId+"'");
            for (String filed : fileds) {
                //判断数据库表字段是否包含页面提交的字段
                if(table.containsKey(filed)) {
                    String v = filedValues.get(filed) + "";
                    if (StrUtil.isNotEmpty(v)) {
                        filedsB.append("," + filed);
                        filedsVB.append(",'" + filedValues.get(filed) + "'");
                    }
                }
            }
            this.baseMapper.insertBusiData(String.format("INSERT INTO %s (%s) VALUES (%s)",tableName,filedsB.toString(),filedsVB.toString()));
        }else { //有，修改
            StringBuilder setSql = new StringBuilder();
            for (String filed : fileds) {
                //判断数据库表字段是否包含页面提交的字段
                if(table.containsKey(filed)) {
                    String parameter = filedValues.get(filed) + "";
                    if (StrUtil.isEmpty(parameter)) {
                        setSql.append(String.format("%s = null,", filed));
                    } else {
                        setSql.append(String.format("%s = '%s',", filed, parameter));
                    }
                }
            }
            String substring = setSql.substring(0, setSql.length()-1);//去掉最后一个,号
            this.baseMapper.updateBusiData(String.format("update %s set %s where id = '%s'",tableName,substring,tableId));
        }
    }

    public Map<String, Object> getApplyForm(String tableId, String tableName) {
        return this.baseMapper.getBusiData(tableId, tableName);
    }

    public void deleteBusiness(String tableName, String tableId) {
        this.baseMapper.deleteBusiData(tableId,tableName);
    }
    /**
     *通过类型和任务id查找用户id
     * */
    public String findUserIdByTypeAndTaskId(String type, String taskId) {
        return this.baseMapper.findUserIdByTypeAndTaskId(type, taskId);
    }

    public void insertHiIdentityLink(String id, String type, String userId, String taskId, String procInstId) {
        this.baseMapper.insertHiIdentityLink(id, type, userId, taskId, procInstId);
    }

    public List<String> selectIRunIdentity(String taskId, String type) {
        return this.baseMapper.selectIRunIdentity(taskId,type);
    }
    /**修改业务表的流程字段*/
    public void updateBusinessStatus(String tableName, String tableId, String actStatus) {
        try {
            this.baseMapper.updateBusinessStatus(tableName,tableId,actStatus);
        } catch (Exception e) {
            // 业务表需要有 act_status字段，没有会报错，不管他
            e.printStackTrace();
        }
    }

    public void editFormData(String tableId, Map<String, Object> paramMap) {
        String tableName = String.valueOf(paramMap.get("tableName"));
        String filedNames = String.valueOf(paramMap.get("filedNames"));
        Map<String,Object> filedValues = (Map<String, Object>) paramMap.get("formDataMap");
        String[] fileds = filedNames.split(",");
        if (StrUtil.isEmpty(tableId)){ //没有，新增逻辑
            tableId = IdUtil.simpleUUID();
            StringBuilder filedsB = new StringBuilder("id");
            StringBuilder filedsVB = new StringBuilder("'"+tableId+"'");
            for (String filed : fileds) {
                String v = filedValues.get(filed)+"";
                if(StrUtil.isNotEmpty(v)){
                    filedsB.append(","+filed);
                    filedsVB.append(",'"+filedValues.get(filed)+"'");
                }
            }
            this.baseMapper.insertBusiData(String.format("INSERT INTO %s (%s) VALUES (%s)",tableName,filedsB.toString(),filedsVB.toString()));
        }else { //有，修改
            //Map<String, Object> busiData = this.baseMapper.getBusiData(tableId, tableName);
            StringBuilder setSql = new StringBuilder();
            for (String filed : fileds) {
                String parameter = filedValues.get(filed)+"";
                if (StrUtil.isEmpty(parameter)){
                    setSql.append(String.format("%s = null,",filed));
                }else {
                    setSql.append(String.format("%s = '%s',",filed, parameter));
                }
            }
            String substring = setSql.substring(0, setSql.length()-1);//去掉最后一个,号
            this.baseMapper.updateBusiData(String.format("update %s set %s where id = '%s'",tableName,substring,tableId));
        }
    }
}
